package com.bittech.facerecognition.web;

import org.apache.commons.codec.digest.DigestUtils;
import org.apache.commons.io.IOUtils;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.Part;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;

/**
 * Author: secondriver
 * Created: 2019/5/31
 */
public abstract class ImageBaseServlet extends AbstractBaseServlet {
    
    private String storagePath;
    
    @Override
    public void init() throws ServletException {
        super.init();
        this.storagePath = System.getProperty("user.home") + File.separator + "face";
        File directory = new File(this.storagePath);
        if (!directory.exists()) {
            boolean effect = directory.mkdirs();
            if (!effect) {
                throw new RuntimeException("create face image storage path not failed " + this.storagePath);
            }
        }
    }
    
    public String getStoragePath() {
        return this.storagePath;
    }
    
    public String writeImage(HttpServletRequest request, String parameter) {
        try {
            Part part = request.getPart(parameter);
            String filename = DigestUtils.md5Hex(part.getSubmittedFileName() + System.currentTimeMillis());
            try (InputStream in = part.getInputStream();
                 OutputStream out = new FileOutputStream(new File(this.storagePath, filename))
            ) {
                IOUtils.write(IOUtils.toByteArray(in), out);
            }
            return filename;
        } catch (IOException | ServletException e) {
            e.printStackTrace();
        }
        return null;
    }
    
    public byte[] readImage(HttpServletRequest request, String parameter) {
        try {
            String filename = request.getParameter(parameter);
            try (InputStream in = new FileInputStream(new File(this.storagePath, filename))
            ) {
                return IOUtils.toByteArray(in);
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
        return null;
    }
}